package com.item.util;

import com.alibaba.fastjson.JSONObject;
import com.item.filter.RequestWrapper;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhang-rongyao
 * @version V1.0
 * @Package com.item.model.util
 * @date 2021/7/23 10:36
 */
public class RequestsUtil {

    public static HttpServletRequest getHttpServletRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return attributes.getRequest();
    }

    /**
     * Get请求获取参数转化成map
     *
     * @param request
     * @return
     */
    public static Map<String, String> getParameterMapInfo(HttpServletRequest request) {
        Enumeration<String> parameterNames = request.getParameterNames();
        HashMap<String, String> map = new HashMap<>(16);
        while (parameterNames.hasMoreElements()) {
            String name = parameterNames.nextElement();
            map.put(name, request.getParameter(name));
        }
        return map;
    }

    /**
     * Get请求获取参数转化成json
     *
     * @param request
     * @return
     */
    public static JSONObject getParameterJsonInfo(HttpServletRequest request) {
        Enumeration<String> parameterNames = request.getParameterNames();
        JSONObject json = new JSONObject();
        while (parameterNames.hasMoreElements()) {
            String name = parameterNames.nextElement();
            json.put(name, request.getParameter(name));
        }
        return json;
    }

    /**
     * Post请求获取参数转化成json
     * 表单提交
     *
     * @param request
     * @return
     */
    public static JSONObject getParameterJson(HttpServletRequest request) throws UnsupportedEncodingException {

        String parameterNames = ((RequestWrapper) request).getBody();
        JSONObject json = new JSONObject();
        if (parameterNames.length() > 0) {
            String[] parameter = parameterNames.split("&");
            for (String a : parameter) {
                String[] param = a.split("=");
                json.put(param[0], URLDecoder.decode(param[1], "UTF-8"));
            }
        }
        return json;
    }


    /**
     * 获取头信息
     *
     * @param request
     * @return
     */

    private static Map<String, String> getHeadersInfo(HttpServletRequest request) {
        Map<String, String> map = new HashMap<String, String>(16);
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        return map;
    }


    /**
     * POST请求获取参数转化成json
     * json提交
     * <p>
     * 注意搭配HttpServletFilter使用
     * 就是通过重写HttpServletRequestWrapper把request的保存下来，
     * 然后通过过滤器保存下来的request在填充进去，这样就可以多次读取request了
     *
     * @param request
     * @return
     * @throws IOException
     */
    public static JSONObject getRequestJsonObject(HttpServletRequest request) throws IOException {
        String json = getRequestJsonString(request);
        return JSONObject.parseObject(json);
    }

    /***
     * 获取 request 中 json 字符串的内容
     *
     * @param request
     * @return : <code>byte[]</code>
     * @throws IOException
     */
    public static String getRequestJsonString(HttpServletRequest request) throws IOException {
        String submitMehtod = request.getMethod();
        // GET
        if ("GET".equals(submitMehtod)) {
            return new String(request.getQueryString().getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8).replaceAll("%22", "\"");
            // POST
        } else {
            return getRequestPostStr(request);
        }
    }

    /**
     * 描述:获取 post 请求的 byte[] 数组
     * <pre>
     * 举例：
     * </pre>
     *
     * @param request
     * @return
     * @throws IOException
     */
    public static byte[] getRequestPostBytes(HttpServletRequest request)
            throws IOException {
        int contentLength = request.getContentLength();
        if (contentLength < 0) {
            return null;
        }
        byte buffer[] = new byte[contentLength];
        for (int i = 0; i < contentLength; ) {

            int readlen = request.getInputStream().read(buffer, i,
                    contentLength - i);
            if (readlen == -1) {
                break;
            }
            i += readlen;
        }
        return buffer;
    }

    /**
     * 描述:获取 post 请求内容
     * <pre>
     * 举例：
     * </pre>
     *
     * @param request
     * @return
     * @throws IOException
     */
    public static String getRequestPostStr(HttpServletRequest request)
            throws IOException {

        byte buffer[] = getRequestPostBytes(request);
        String charEncoding = request.getCharacterEncoding();
        if (charEncoding == null) {
            charEncoding = "UTF-8";
        }
        return new String(buffer, charEncoding);

    }
}
